package com.taikang.hmp.hbusiness.doctor.setbase.action.intface;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.hmp.business.ticket.common.servicefacade.TicketsBizFacade;
import com.taikang.hmp.frame.common.ErrorConstant;
import com.taikang.hmp.frame.common.TKException;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.datastructre.support.ResponseDto;
import com.taikang.hmp.frame.common.tools.MD5Util;
import com.taikang.hmp.frame.common.validate.validator.internal.MobilePhoneValidator;
import com.taikang.hmp.frame.common.web.action.BaseAction;
import com.taikang.hmp.frame.common.web.session.AppSessionFactory;
import com.taikang.hmp.frame.common.web.session.SessionBean;
import com.taikang.hmp.frame.customer.bean.CustomerInfo;
import com.taikang.hmp.hbusiness.doctor.setbase.service.IUserBaseService;

public class UserBaseAction extends BaseAction {
	private static final long serialVersionUID = 1L;

	private static Logger logger = LoggerFactory.getLogger(UserBaseAction.class);
	
	private static MobilePhoneValidator mobilePhoneValidator = new MobilePhoneValidator();
	private IUserBaseService userBaseService;
	
	private TicketsBizFacade ticketsBizFacade;
	
	public IUserBaseService getUserBaseService() {
		return userBaseService;
	}

	public void setUserBaseService(IUserBaseService userBaseService) {
		this.userBaseService = userBaseService;
	}
	
	public TicketsBizFacade getTicketsBizFacade() {
		return ticketsBizFacade;
	}

	public void setTicketsBizFacade(TicketsBizFacade ticketsBizFacade) {
		this.ticketsBizFacade = ticketsBizFacade;
	}

	@Override
	public String executeAction() {
		if ("getUserBaseInformation".equals(requestDto.getMethod())) {
			logger.info("--得到个人基本信息 getUserBaseInformation method -- ");
			return getUserBaseInformation();
		
		} else if("updateUserBaseInformation".equals(requestDto.getMethod())){
			logger.info("--更新用户基本信息 updateUserBaseInformation method -- ");
			return updateUserBaseInformation();
		}else if ("updateActivation".equals(requestDto.getMethod())) {
			logger.info("--激活 activation method -- ");
			return updateActivation();
		
		}else if ("getDate".equals(requestDto.getMethod())) {
			logger.info("--我的服务 getDate method -- ");
			return getDate();
		
		}else if ("upatePassword".equals(requestDto.getMethod())) {
			logger.info("--更改密码upatePassword method -- ");
			return upatePassword();
		}else if ("updateImage".equals(requestDto.getMethod())) {
			logger.info("--上传头像updateImage method -- ");
			return updateImage();
		}else if ("updateIcon".equals(requestDto.getMethod())) {
			logger.info("--上传头像updateIcon method -- ");
			return updateIcon();
		}else if ("testUdp".equals(requestDto.getMethod())) {
			logger.info("--压力测试UDP-RPC method -- ");
			return testPressureNoData();
		}else {
			throw new TKException("no support method:" + requestDto.getMethod());
		}
	}
	/**
	 * 上传头像
	 * @return
	 */
	private String testPressureNoData() {
		logger.error("--------------------------请求进入UDP客户端!");
		ResponseDto responseDto = new ResponseDto();
		//获取参数
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		
		boolean error =false;
		com.taikang.framework.common.datastructre.RequestDto frameReqdto = new com.taikang.framework.common.datastructre.RequestDto("","hdhealth","hdhealth");
		com.taikang.framework.common.datastructre.Dto frameDto = new com.taikang.framework.common.datastructre.impl.BaseDto();
		frameDto.put("contId", "0");
		frameReqdto.setRequestParam(frameDto);
		logger.error("--------------------------开始请求UDP服务器端!");
		com.taikang.framework.common.datastructre.ResponseDto frameResponse = ticketsBizFacade.qryTicketByContId(frameReqdto);
		logger.error("--------------------------UDP服务器端返回消息!");
		if(!frameResponse.isSucess()){
			error = true;
			responseDto.addError(frameResponse.getErrorMsg());
			logger.error("--------------------------请求返回失败!");
		}else{
			logger.error("--------------------------请求返回成功!");
		}	
		
		super.setDataMap(responseDto);
		return SUCCESS;
	}

	/**
	 * 上传头像
	 * @return
	 */
	private String updateIcon() {
		ResponseDto responseDto = new ResponseDto();
		//获取参数
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		
		boolean info = userBaseService.saveHeadImage(paramDto);
		if(info){
			logger.info("...........头像保存成功...........");
			String sessionId = requestDto.getSessionid();
			SessionBean sessionBean = AppSessionFactory.getInstance(requestDto.getRequestsource()).isSessionTimeout(sessionId);
			if(sessionBean != null){	
				String uid = paramDto.getAsString("uid");
				userBaseService.saveBasicInfo(paramDto);
				//保存以及修改及时更新session中的信息,以确保最新
				sessionBean = userBaseService.getCustomerBasicInfo(uid,sessionBean);
				AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionId,sessionBean);
				//AppUidStatusFactory.getInstance().loginSuccess(uid);
			}else{
				responseDto.addErrorCode(ErrorConstant.SESSION_TIMEOUT);
			}
		}else{
			logger.info("...........头像保存失败...........");
			responseDto.addError(ErrorConstant.ICON_FAIL);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	/**
	 * 上传头像
	 * @return
	 */
	private String updateImage() {
		ResponseDto responseDto = new ResponseDto();
		//获取参数
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		
		boolean info = userBaseService.saveImage(paramDto);
		if(info){
			logger.info("...........头像保存成功...........");
			String sessionId = requestDto.getSessionid();
			SessionBean sessionBean = AppSessionFactory.getInstance(requestDto.getRequestsource()).isSessionTimeout(sessionId);
			if(sessionBean != null){	
				String uid = paramDto.getAsString("uid");
				userBaseService.saveBasicInfo(paramDto);
				//保存以及修改及时更新session中的信息,以确保最新
				sessionBean = userBaseService.getCustomerBasicInfo(uid,sessionBean);
				AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionId,sessionBean);
				//AppUidStatusFactory.getInstance().loginSuccess(uid);
			}else{
				responseDto.addErrorCode(ErrorConstant.SESSION_TIMEOUT);
			}
		}else{
			logger.info("...........头像保存失败...........");
			responseDto.addError(ErrorConstant.ICON_FAIL);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}

	//获取客户的基本信息，从session中获取
	private String getUserBaseInformation() {
		/*ResponseDto responseDto = new ResponseDto();
		
		//获取参数
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		List<Dto> resultList = userBaseService.getUserBaseInformation(paramDto);
		return SUCCESS;*/
		ResponseDto responseDto = new ResponseDto();
		
		// 寻找session
		String sessionId = requestDto.getSessionid();
		SessionBean sessionBean = AppSessionFactory.getInstance(requestDto.getRequestsource()).isSessionTimeout(sessionId);
		if (sessionBean != null) {
			if (sessionBean.getCustomerInfo() == null) {
				responseDto.addErrorCode(ErrorConstant.HD_CUSTOMER_BASE_DATA_NULL);
			} else {
				Dto dto = new BaseDto();
				dto.put("name", sessionBean.getCustomerInfo().getName());
				dto.put("mobile", sessionBean.getCustomerInfo().getMobile());
				dto.put("birthday", sessionBean.getCustomerInfo().getBirthday());
				dto.put("sex", sessionBean.getCustomerInfo().getSex());
				dto.put("height", sessionBean.getCustomerInfo().getHeight());
				dto.put("weight", sessionBean.getCustomerInfo().getWeight());
				dto.put("head_image", sessionBean.getCustomerInfo().getHead_image());
				responseDto.pushResultDto(dto);
			}
		} else {
			responseDto.addErrorCode(ErrorConstant.SESSION_TIMEOUT);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	
	
	//更新客户基本信息
	private String updateUserBaseInformation() {
		ResponseDto responseDto = new ResponseDto();
		
		//获取参数
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		String uid = paramDto.getAsString("uid");
		
		//寻找session
		String sessionId = requestDto.getSessionid();
		SessionBean sessionBean = AppSessionFactory.getInstance(requestDto.getRequestsource()).isSessionTimeout(sessionId);
		if(sessionBean != null){	
			userBaseService.saveBasicInfo(paramDto);
			//保存以及修改及时更新session中的信息,以确保最新
			sessionBean = userBaseService.getCustomerBasicInfo(uid,sessionBean);
			AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionId,sessionBean);
			//AppUidStatusFactory.getInstance().loginSuccess(uid);
		}else{
			responseDto.addErrorCode(ErrorConstant.SESSION_TIMEOUT);
		}
		
		//
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	

	//更新密码
	private String upatePassword() {
		boolean error = false;
		ResponseDto responseDto = new ResponseDto();
		
		//获取参数
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		
		//密码验证
		if( !userBaseService.check_password_true(paramDto) ){
			logger.info("-----------------------密码错误！");
			error = true;
			responseDto.addErrorCode(ErrorConstant.HD_PASSWORD_OLDERR);
		}
		if(error){
			super.setDataMap(responseDto);
			return SUCCESS;
		}
		if(!error){
			//更新密码
			userBaseService.updatePassword(paramDto);
			logger.info("--------------------更改密码成功！------------");
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	

	//我的服务
	private String getDate() {
		ResponseDto responseDto = new ResponseDto();
		
		//获取参数
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		String uid = paramDto.getAsString("uid");
		
		List<Dto> serviceDate = userBaseService.getServiceDate(uid);
		Dto resultDto = new BaseDto();
		resultDto.put("resultlist", serviceDate);
		responseDto.pushResultDto(resultDto);
		super.setDataMap(responseDto);
		return SUCCESS;
	}

	

	//用户产品激活
	private String updateActivation() {
		boolean error = false;
		logger.error("-----------------------用户开始激活");
		ResponseDto responseDto = new ResponseDto();
		
		//获取参数
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		String uid = paramDto.getAsString("uid");
		
		Integer is_exit_act = userBaseService.check_activationcode_exist(paramDto.getAsString("code").toUpperCase());
		logger.error("-----------------------error:"+error);
		logger.error("-----------------------is_exit_act:"+is_exit_act);
		
		
		 if(is_exit_act==2){
			logger.error("--------------------------该产品激活码不存在");
			error = true;
			responseDto.addErrorCode(ErrorConstant.HD_ACTIVATIONCODE_NOT_EXIST);
		}else if(is_exit_act==1){
			logger.error("--------------------------该产品激活码已使用");
			error = true;
			responseDto.addErrorCode(ErrorConstant.HD_ACTIVATIONCODE_USE_EXIST);
		}else if (is_exit_act==0) {	
			
			SessionBean sessionBean = AppSessionFactory.getInstance(requestDto.getRequestsource()).isSessionTimeout(requestDto.getSessionid());
			//
			String mobile = sessionBean.getCustomerInfo().getMobile();
			if(StringUtils.isEmpty(mobile) || !mobilePhoneValidator.isValid(mobile)){
				error = true;
				responseDto.addError(mobile+":无效手机号");
				logger.error(mobile+":无效手机号");
			}
			
		    if(!error){
		    	logger.error("开始开通一键问医......");
				//一键问医
				com.taikang.framework.common.datastructre.RequestDto frameReqdto = new com.taikang.framework.common.datastructre.RequestDto("","hdhealth","hdhealth");
				com.taikang.framework.common.datastructre.Dto frameDto = new com.taikang.framework.common.datastructre.impl.BaseDto();
				frameDto.put("cpnCode", "151101-6-1-1");
				frameDto.put("sourceCd", "APP_DOCTOR");
				frameDto.put("sourceClientId", sessionBean.getCustomerInfo().getCustomer_id());
				frameDto.put("countTypeCd", "HMP");
				frameDto.put("tickSourceCd", "HMP");
				frameDto.put("mobilePhone", mobile);
				frameDto.put("contName", paramDto.getAsString("name"));
				frameReqdto.setRequestParam(frameDto);
				//addTicketByInsur,qryTicketByContId,updateTicketStatusByTicketNo,updateTicketPhoneByTicketNo,addTicketByRcvId,addTicketByClientId,isMobileUsedByCpnCd,qryTicketByTicketNo,qryTicketPhoneByTicketNo,qryTicketKeyInfoByTicketNo,qryTicketByContIdAndSSN,qryTicketBySSNAndSourceChlCd
				com.taikang.framework.common.datastructre.ResponseDto frameResponse = ticketsBizFacade.addTicketByClientId(frameReqdto);
				if(!frameResponse.isSucess()){
					error = true;
					responseDto.addError(frameResponse.getErrorMsg());
					logger.error("--------------------------一键问医失败!");
				}else{
					logger.error("--------------------------一键问医成功!");
				}
		    }	
		}
		 
		if(error){
			super.setDataMap(responseDto);
			return SUCCESS;
		}
		if(!error){
			//更新真实姓名到库
			SessionBean sessionInfo = AppSessionFactory.getInstance(requestDto.getRequestsource()).isSessionTimeout(paramDto.getAsString("sessionid"));
			CustomerInfo info = sessionInfo.getCustomerInfo();
			info.setName(paramDto.getAsString("name"));
			logger.error("-----------------------更新用户真实姓名------------------");
			userBaseService.updateCustomerInfo(info);
			logger.error("-----------------------用户产品激活------------------");
			userBaseService.saveActivation(paramDto);
			//寻找session
			String sessionId = requestDto.getSessionid();
			SessionBean sessionBean = AppSessionFactory.getInstance(requestDto.getRequestsource()).isSessionTimeout(sessionId);
			//保存以及修改及时更新session中的信息,以确保最新
			sessionBean = userBaseService.getCustomerBasicInfo(uid,sessionBean);
			AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionId,sessionBean);
			//AppUidStatusFactory.getInstance().loginSuccess(uid);
			//更新激活时间
			userBaseService.updateCustomerUCM(info);
		}
		Dto dto = new BaseDto();
		String is_act = "0";
		dto.put("is_act", is_act);
		String checkStr = requestDto.getRequestid()+is_act+paramDto.getAsString("uid");
		dto.put("checkStr", MD5Util.stringMD5(checkStr));
		responseDto.pushResultDto(dto);
		super.setDataMap(responseDto);
		return SUCCESS;
	}
}
